package _17_剑指Offer;

import _17_剑指Offer.datastrcute.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class _32_剑指Offer从上到下打印二叉树II {

    List<List<Integer>> results = new ArrayList<>();

    // DFS遍历，当前DFS层数也就是数组下标元素
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return results;

        dfs(root, 0);
        return results;
    }

    private void dfs(TreeNode root, int depth) {
        if (root == null) return;

        if (depth == results.size()) {
            results.add(new ArrayList<>());
        }

        results.get(depth).add(root.val);

        dfs(root.left, depth + 1);
        dfs(root.right, depth + 1);
    }


    // 遍历完当前队列所有元素
    public List<List<Integer>> levelOrder2(TreeNode root) {
        List<List<Integer>> results = new ArrayList<>();
        if (root == null) return results;

        // 二叉树层序遍历
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            // 把当前队列中所有元素遍历
            for (int i = queue.size(); i > 0; i--) {
                TreeNode node = queue.poll();
                list.add(node.val);

                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            results.add(list);
        }
        return results;
    }

    // 层序遍历
    public List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> results = new ArrayList<>();
        if (root == null) return results;

        // 二叉树层序遍历
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<Integer> list = new ArrayList<>();
        int size = queue.size();
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            list.add(node.val);
            if (node.left != null) queue.offer(node.left);

            if (node.right != null) queue.offer(node.right);
            if (--size == 0) {
                // 当前层数遍历完成
                results.add(list);
                list = new ArrayList<>();
                size = queue.size();
            }
        }
        return results;
    }

}
